<?php
namespace app\mobile\controller;

use app\model\Theme; 
use app\model\Poster; 

class Clive extends Base
{
    public function Clive()
    {
global $_G, $_P;
$themeid = $_P["themeid"];
$op = $_P["op"];
if ($op == 'sub') {
    $uid = $_G['member']['uid'];
    $r = db_update(t_fans, array("sublive" => 1), array("themeid" => $themeid, "id" => $uid));
    return $this->result(0, $r ?  "订阅成功" : "订阅失败");
} else if ($op == 'notify') {
    $total = 0;
    $users = db_getslice(t_fans, array("themeid" => $themeid, "sublive" => 1, "msgstatus" => 0), array(0, 10), $total, array("openid"));
    if (empty($users)) {
        $c = Theme::getConfig($themeid);
        $c ['sendnotify'] = 0;
        Theme::setConfig($c,$themeid,2);
        return;
    }
    $theme = Theme::getThemeByIdxcx($themeid);
    $userparams = str_replace("[", "", json_encode(array_column($users, "openid")));
    $userparams = str_replace("]", "", $userparams);
    $userparams =  str_replace('"', "'", $userparams);
    if (!empty($userparams)) {
        db_query("update " . tablename(t_fans) . " set msgstatus = 1 where themeid=:tid and openid in (" . $userparams . ")", array(":tid" => $themeid));
    }
    $system = $_G['system'];
    
function SendSubMsg($toUser, $params, $access_token)
    { 
        $url =  "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" . $access_token;
        $ch1 = curl_init();
        $params['touser'] = $toUser;
        curl_setopt($ch1, CURLOPT_URL, $url);
        curl_setopt($ch1, CURLOPT_POST, 1);
        curl_setopt($ch1, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch1, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch1, CURLOPT_POSTFIELDS,  json_encode($params));
        $res = curl_exec($ch1);
        return json_decode($res, true);
    }
    $access_token = Poster::getAccessToken($system);
    $config =  Theme::getConfig($themeid);
    $startTime = $config['livedata']['livetime'];
    foreach ($users as  $u) {
        $params['template_id'] = $system['livetemplate'];
        $params['data'] = [
            'thing2' => ['value' => $startTime],
            'thing1' => ['value' => $config['livedata']['lname']]
        ];
        $params['page'] = "index";
        $r = self::SendSubMsg($u['openid'], $params, $access_token);
        $finish = $r['errcode'] == 43101 || $r['errcode'] == 0;
        db_update(t_fans, array("msgstatus" => $finish ? 2 : 0), array("themeid" => $themeid, "openid" => $u['openid']));
    }
}else if($op == "livesfinish"){
    $config = Theme::getConfig($themeid);
    $config['livedata']['livestatus'] = "103";
    Theme::setConfig($config,$themeid,0);
}
}
}